package com.happycat.provider;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.happycat.config.HappyCatSecurity;
import com.happycat.mobile.model.UserAccount;
import com.happycat.mobile.service.UserAccountService;
import com.happycat.utils.AesUtils;

@Component
public class HappyCatAuthenticationProvider implements AuthenticationProvider {
	
	@Resource
	private UserAccountService userAccountService;
	
	@Resource
	private PasswordEncoder passwordEncoder;	
	
	@Autowired
	private HappyCatSecurity happyCatSecurity;

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		//获取输入的用户名
        String username = authentication.getName();
        //查询用户是否存在
        UserAccount userAccount = new UserAccount();
        userAccount.setAccountName(username);
        Wrapper<UserAccount> queryWrapper = new QueryWrapper<>(userAccount);
        userAccount = userAccountService.getOne(queryWrapper);
       
        //获取输入的密文文
        String aesPassword = (String) authentication.getCredentials();
        String rawPassword = AesUtils.decrypt(aesPassword, happyCatSecurity.getAesKey());
        //查询用户是否存在
        UserAccount accountParam = new UserAccount();
        accountParam.setAccountName(username);
        UserAccount account = (UserAccount) userAccountService.getAccountMappingRoleList(accountParam);
        //验证密码
        if (!passwordEncoder.matches(rawPassword, account.getPassword())) {
            throw new BadCredentialsException("输入密码错误!");
        }                         
        return new UsernamePasswordAuthenticationToken(account, rawPassword, account.getAuthorities());
	}

	@Override
	public boolean supports(Class<?> authentication) {
		
		return authentication.equals(UsernamePasswordAuthenticationToken.class);
	}

}
